import wx
import wx.adv
import base64
from io import BytesIO
import threading
import asyncio
import sys
import time
import os

import images
import key_mouse_api
import async_user


class mythread(threading.Thread):
    def __init__(self,windows):
        threading.Thread.__init__(self)
        self.daemon = True
        self.windows = windows
        self.loop = asyncio.new_event_loop()

    def run(self):
        try:
            asyncio.set_event_loop(self.loop)
            self.loop.run_until_complete(async_user.async_main(self.windows))
        except RuntimeError:
            pass

    def mystop(self,code):
        self.windows.queue.put({"type":"close"})
        n_loop = asyncio.new_event_loop()
        n_loop.run_until_complete(self._Stop(code))
        n_loop.close()
		
    async def _Stop(self,code):
        if self.loop.is_running():
            try:
                time.sleep(0.5)
                self.loop.close()
            except RuntimeError:
                self.windows.queue.put({"type":"close"})
                future = asyncio.Future(loop=self.loop)
                future.cancel()
                self.loop.call_soon_threadsafe(self.loop.stop)
                time.sleep(0.5)
                await self._Stop(code)
        if code == 1000:
            thr = threading.Thread(target=key_mouse_api.shell_wondow,args=(os.path.abspath(sys.argv[0])+ " run",))
            thr.daemon = True
            thr.start()
        wx.Exit()
        sys.exit() 


class MyFramelogin(wx.Frame):
    def __init__(self,parent,queue):
        wx.Frame.__init__(self,parent,size=wx.Size(300,80),title='回车执行',style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER|wx.MAXIMIZE_BOX))
        font10 = wx.Font(15, wx.MODERN, wx.NORMAL, wx.NORMAL, False, '华文行楷')
        self.queue = queue
        self.Centre(wx.BOTH)
        
        self.update_TextCtrl = wx.TextCtrl(self, value=u"", pos=(90,5),size=wx.Size(190, 30),style=wx.TE_PROCESS_ENTER)
        self.text_StaticText = wx.StaticText(self, label=u"", pos=(5,10),size=wx.Size(30, 30),style=wx.ALIGN_CENTRE_HORIZONTAL)
        self.update_TextCtrl.SetFont(font10)
        self.text_StaticText.SetFont(font10)
        self.update_TextCtrl.Bind(wx.EVT_TEXT_ENTER, self.on_update)
        self.Bind(wx.EVT_CLOSE, self.on_cloase)
        self.update_TextCtrl.SetDropTarget(FileDrop(self.update_TextCtrl))

        self.folder = FolderBookmarkTaskBarIcon(self)
        self.mythr = mythread(self)
        self.mythr.start()

    def on_cloase(self,eve):
        self.Show(False)
        
    def on_update(self,eve):
        data = self.update_TextCtrl.GetValue()
        if self.text_StaticText.GetLabel() == "文件路径":
            self.queue.put({"type":"update","msg":data})
            self.update_TextCtrl.SetValue("")
        else:
            ret = wx.MessageBox("修改地址后会立即生效，确定修改吗?", "提示",wx.YES_NO, None)
            if ret == wx.YES:
                key_mouse_api.CONFNG.set_cfg("ip",data)
                key_mouse_api.CONFNG.ip = data
                wx.MessageBox("修改成功", "提示", wx.OK, None)
            else:
                self.update_TextCtrl.SetValue(key_mouse_api.CONFNG.ip)


class FileDrop(wx.FileDropTarget):
    def __init__(self,windows):
        wx.FileDropTarget.__init__(self)
        self.windows = windows

    def OnDropFiles(self, x, y, filePath):
        if filePath:
            for i in filePath:
                self.windows.SetValue(i)
            return True
        else:
            return False


class FolderBookmarkTaskBarIcon(wx.adv.TaskBarIcon):
    TITLE = '客户端'

    MENU_ID1, MENU_ID2, MENU_ID3, MENU_ID4 = wx.NewIdRef(count=4)
    
    def __init__(self,windows):
        super().__init__()
        by = BytesIO(base64.b64decode(images.imge))
        p = wx.Image(by, type=wx.BITMAP_TYPE_ICO)
        by.close()
        wxico = wx.Icon()
        wxico.CopyFromBitmap(wx.Bitmap(p))
        self.SetIcon(wxico, self.TITLE)
        self.Bind(wx.EVT_MENU, lambda evt, mark='update' : self.myshow(evt,mark), id=self.MENU_ID1)
        self.Bind(wx.EVT_MENU, lambda evt, mark='退出' : self.myexit(evt,mark), id=self.MENU_ID2)
        self.Bind(wx.EVT_MENU, lambda evt, mark='重启' : self.myexit(evt,mark), id=self.MENU_ID4)
        self.Bind(wx.EVT_MENU, lambda evt, mark='setdat' : self.myshow(evt,mark), id=self.MENU_ID3)
        self.windows = windows


    def CreatePopupMenu(self):
        self.menu = wx.Menu()
        self.menu.Append(self.MENU_ID1, '上传包')
        self.menu.Append(self.MENU_ID3, '设置')
        self.menu.Append(self.MENU_ID4, '重启')
        self.menu.Append(self.MENU_ID2, '退出')
        return self.menu

    def myshow(self, event, mak):
        if mak == 'update':
            self.windows.text_StaticText.SetLabel("文件路径")
            self.windows.update_TextCtrl.SetValue("")
        else:
            self.windows.text_StaticText.SetLabel("主机地址")
            self.windows.update_TextCtrl.SetValue(key_mouse_api.CONFNG.ip)
        self.windows.Show(True)
        self.windows.ToggleWindowStyle(wx.STAY_ON_TOP)
        self.windows.ToggleWindowStyle(wx.STAY_ON_TOP)

    def myexit(self, event, mak):
        ret = wx.MessageBox("确定{}吗？".format(mak), "提示",wx.YES_NO, None)
        if ret == wx.YES:
            if mak == "重启":
                threading.Thread(target=self.windows.mythr.mystop,args=(1000,)).start()
            else:
                threading.Thread(target=self.windows.mythr.mystop,args=(2000,)).start()
            #self.windows.Destroy()
            #self.Destroy()
